//
//  BookDetailVC.m
//  Cunli
//
//  Created by lilubin on 15/7/27.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "BookDetailVC.h"
#import "BookDetailModel.h"
#import "BookDetailHeaderView.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "EPubVC.h"
#import "HYActivityView.h"
#import "ReportDetailVC.h"
#import "UIColor+expanded.h"

//#import "UMSocial.h"
//#import "UMSocialWechatHandler.h"
//#import "UMSocialQQHandler.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height


@interface BookDetailVC () <UIWebViewDelegate, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UIWebView *_catelogWebView;      //目录的webview
    CGFloat _webCellHeight;
    double _total;                   //数据总长度
    NSMutableData *_totalData;       //下载的总数据
    MBProgressHUD *_HUD;
}

@property (nonatomic, strong) BookDetailModel *detailModel; //详情model
@property (nonatomic, strong) HYActivityView *activityView; //弹出视图
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation BookDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"详情";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-44) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self createBackBtn];
    [self setAttributesAboutWebView];
    [self loadDetailData];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"0xf6f6f6"]];
    [self.tableView setBackgroundColor:[UIColor colorWithHexString:@"0xf6f6f6"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)createBackBtn
{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 20);
    [rightBtn setImage:[UIImage imageNamed:@"nav_right_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setAttributesAboutWebView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    CGRect newFrame = self.view.bounds;
    CGFloat newHeight = 100;
    newFrame.size.height = newHeight;
    //_detailWebView.frame = newFrame;
    
    _catelogWebView = [[UIWebView alloc] initWithFrame:newFrame];
//    _catelogWebView.backgroundColor = [UIColor colorWithHexString:@"0xf6f6f6"];
    [_catelogWebView setBackgroundColor:[UIColor clearColor]];
    [_catelogWebView setOpaque:NO];
    _catelogWebView.delegate = self;
    _catelogWebView.scrollView.delegate = self;
    _catelogWebView.scrollView.bounces = NO;
    _catelogWebView.translatesAutoresizingMaskIntoConstraints = NO;
    _catelogWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    if (section == 0) {
    //        return 0;
    //    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    if (section == 0) {
    //        return 1;
    //    }
    return 40;
}

/*
 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
 {
 if (section == 2) {
 return 120;
 }
 return 1;
 }
 */

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 100, 40)];
//    label.backgroundColor= [UIColor whiteColor];
    if (section == 0) {
        label.text = @"内容简介:";
    }
    else if(section == 1)
    {
        label.text = @"目录:";
    }
    label.font = [UIFont boldSystemFontOfSize:17];
    [sectionView setBackgroundColor:[UIColor colorWithHexString:@"0xf6f6f6"]];
    [sectionView addSubview:label];
    return sectionView;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIColor *bgColor = [UIColor colorWithHexString:@"0xf6f6f6"];
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    if (indexPath.section == 0) {
        cell.textLabel.text = _detailModel.introduce;
        cell.backgroundColor = bgColor;
        cell.textLabel.numberOfLines = 0;
    }
    else if(indexPath.section == 1)
    {
        [cell.contentView addSubview:_catelogWebView];
        NSString *catelogHtmlStr = [NSString stringWithFormat:@"<html><body>%@</body></html>", _detailModel.catelog];
        [_catelogWebView loadHTMLString:catelogHtmlStr baseURL:nil];
        cell.contentView.backgroundColor = bgColor;
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = bgColor;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return _webCellHeight;
    }
    UILabel *propertyLabel = [UILabel new];
    propertyLabel.font = [UIFont systemFontOfSize:17];
    propertyLabel.text = _detailModel.introduce;
    propertyLabel.numberOfLines = 0;
    CGSize newlabelSize = [_detailModel.introduce boundingRectWithSize:CGSizeMake(kScreenWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
    
    return newlabelSize.height+40;
}

- (void)createHeaderView
{
    BookDetailHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"BookDetailHeaderView" owner:self options:nil] lastObject];
    headerView.detailModel = _detailModel;
    self.tableView.tableHeaderView = headerView;
    
    headerView.buttonClicked = ^(NSInteger index){
        if (index == 1) {
            [self addStudyAction];
        }
        else
        {
            [self startStudyAction];
        }
    };
}

//加入学习
- (void)addStudyAction
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:self.bookID forKey:@"itemid"];
    [CheckParams setObject:@"23" forKey:@"item_mid"];
    [CheckParams setObject:@"2" forKey:@"type"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"add_favorite.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        
        if ([result[@"response"] isEqualToString:@"add_favorite"]) {
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"加入学习成功";
        }else
        {
            NSString *reason = [result[@"error"] objectForKey:@"text"];
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = reason;
        }
        [hud hide:YES afterDelay:1];
    } failureAction:^{
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"加入学习失败";
        [hud hide:YES afterDelay:1];
    }];
}

- (void)startStudyAction
{
    if (_detailModel.resources.length != 0) {
        NSURL *url = [NSURL URLWithString:_detailModel.resources];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection connectionWithRequest:request delegate:self];
        _HUD = [Config createHUD];
        _HUD.userInteractionEnabled = NO;
    }
    else
    {
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"本书未上传";
        [hud hide:YES afterDelay:1];
    }
}

#pragma mark - 文件下载代理协议
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    NSDictionary *fields = [httpResponse allHeaderFields];
    
    NSNumber *length = fields[@"Content-Length"];
    _total = [length doubleValue];
    
    _totalData = [[NSMutableData alloc] init];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [_totalData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    NSURL *url = connection.currentRequest.URL;
    
    NSString *urlStr = url.absoluteString;
    
    //取得URL的最后一部分 music.mp3
    NSString *fileName = [urlStr lastPathComponent];
    //拼接路径
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
    
    [_totalData writeToFile:path atomically:YES];
    EPubVC *pubVC = [[EPubVC alloc] init];
    pubVC.epubPath = path;
    pubVC.hidesBottomBarWhenPushed = YES;
    [_HUD hide:YES];
    [self.navigationController pushViewController:pubVC animated:YES];
}


- (void)loadDetailData
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_bookID forKey:@"itemid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"studydetail.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        
        if ([response isEqualToString:@"studydetail"]) {
            NSLog(@"In bookDetailVC result:%@", result);
            //            _detailModel = [[BookDetailModel alloc] initWithDataDic:result[@"data"]];
            _detailModel = [BookDetailModel yy_modelWithJSON:result[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            [weakSelf createHeaderView];
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //    NSIndexSet *reloadInset = [[NSIndexSet alloc] initWithIndex:2];
    
    //    NSString *webViewHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
    //    CGRect frame = [webView frame];
    //    frame.size.height = [webViewHeight floatValue] + 5;
    //    [webView setFrame:frame];
    //    NSString *webViewStr = NSStringFromCGRect(webView.frame);
    //    NSString *webContentStr = NSStringFromCGRect(webView.scrollView.frame);
    //    NSLog(@"webViewStr:%@, contentStr:%@", webViewStr, webContentStr);
    [_HUD hide:YES];
    
    CGFloat contentHeight = webView.scrollView.contentSize.height;
    //    NSLog(@"webViewDidFinishLoad:%f", contentHeight);
    
    CGRect newFrame = webView.frame;
    newFrame.size.height = contentHeight;
    [webView setFrame:newFrame];
    
    _webCellHeight = contentHeight;
    
    //    [self.tableView reloadSections:reloadInset  withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [_HUD hide:YES];
}

- (void)dealloc
{
    _catelogWebView = nil;
}

- (void)popAction:(UIButton *)button
{
    __weak typeof(self) weakSelf = self;
    
    if (!self.activityView) {
        self.activityView = [[HYActivityView alloc]initWithTitle:@"分享到" referView:self.view];
        
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置.
        self.activityView.numberOfButtonPerLine = 6;
        
        /*
         ButtonView *bv = [[ButtonView alloc]initWithText:@"QQ" image:[UIImage imageNamed:@"qq_icon"] handler:^(ButtonView *buttonView){
         [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
         [UMSocialData defaultData].extConfig.qqData.title = weakSelf.detailModel.title;
         
         [UMSocialData defaultData].extConfig.qqData.url = weakSelf.detailModel.share_url;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ] content:weakSelf.detailModel.share_url image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         if (response.responseCode == UMSResponseCodeSuccess) {
         [weakSelf postPointGetRequestWithString:@"4"];
         }
         }];
         
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"QQ空间" image:[UIImage imageNamed:@"qzone_icon"] handler:^(ButtonView *buttonView){
         
         [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
         [UMSocialData defaultData].extConfig.qzoneData.title = weakSelf.detailModel.title;
         [UMSocialData defaultData].extConfig.qzoneData.url = weakSelf.detailModel.share_url;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQzone] content:weakSelf.detailModel.title image:[UIImage imageNamed:@"aboutApp01.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         if (response.responseCode == UMSResponseCodeSuccess) {
         [weakSelf postPointGetRequestWithString:@"3"];
         }
         }];
         
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"微信" image:[UIImage imageNamed:@"wechat_icon"] handler:^(ButtonView *buttonView){
         
         [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
         [UMSocialData defaultData].extConfig.wechatSessionData.url = weakSelf.detailModel.share_url;
         [UMSocialData defaultData].extConfig.title = weakSelf.detailModel.title;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:weakSelf.detailModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         [weakSelf postPointGetRequestWithString:@"1"];
         }];
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"朋友圈" image:[UIImage imageNamed:@"wechat_timeline_icon"] handler:^(ButtonView *buttonView){
         [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
         [UMSocialData defaultData].extConfig.wechatTimelineData.url = weakSelf.detailModel.share_url;
         [UMSocialData defaultData].extConfig.title = weakSelf.detailModel.title;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:weakSelf.detailModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         [weakSelf postPointGetRequestWithString:@"2"];
         }];
         
         }];
         [self.activityView addButtonView:bv];
         */
        
        ButtonView *bv = [[ButtonView alloc]initWithText:@"加入学习" image:[UIImage imageNamed:@"cunli_favorite"] handler:^(ButtonView *buttonView){
            [weakSelf doFavoriteAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"刷新" image:[UIImage imageNamed:@"cunli_refresh"] handler:^(ButtonView *buttonView){
            [weakSelf doRefreshAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"举报" image:[UIImage imageNamed:@"cunli_report"] handler:^(ButtonView *buttonView){
            [weakSelf doReportAction];
        }];
        [self.activityView addButtonView:bv];
        
    }
//    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    if (![Config isShield]) {
        [self.activityView show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

- (void)postPointGetRequestWithString:(NSString *)str
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:4];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_detailModel.itemid forKey:@"item_id"];
    [CheckParams setObject:_detailModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:str forKey:@"channel"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"app_point_share.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result)
     {
         /*
          NSLog(@"In newsDetailController result:%@", result);
          
          if ([result[@"response"] isEqualToString:@"app_point_share"])
          {
          NSLog(@"获取积分成功");
          }
          */
     } failureAction:^{
         //         NSLog(@"获取积分失败");
     }];
}


//收藏文章详情方法
- (void)doFavoriteAction
{
    //    NSLog(@"点击收藏");
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:self.detailModel.itemid forKey:@"itemid"];
    [CheckParams setObject:self.detailModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:@"2" forKey:@"type"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"add_favorite.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        //        NSLog(@"Add favorite result:%@", result);
        
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        
        if ([result[@"response"] isEqualToString:@"add_favorite"])
        {
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"加入学习成功";
        }else
        {
            NSString *reason = [result[@"error"] objectForKey:@"text"];
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = reason;
        }
        [hud hide:YES afterDelay:1];
        
    } failureAction:^{
        //        NSLog(@"Add favorite failed");
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"加入学习失败";
        [hud hide:YES afterDelay:1];
        
    }];
    
}

//刷新文章详情方法
- (void)doRefreshAction
{
}

//举报文章方法
- (void)doReportAction
{
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = self.detailModel.itemid;
    reportVC.m_itemid = self.detailModel.item_mid;
    [self.navigationController pushViewController:reportVC animated:YES];
}

@end
